var selectedRow = null;
// 默认选中事件
var refresh = 0;

function handleServerResult(res) {
    if (refresh == 0 && appid != null && appid != 'null') {
        if (res.list.length > 0)
            for (var i = 0; i < res.list.length; i++) {
                if (res.list[i].appid == appid) {
                    selectedRow = res.list[i];
                }
            }
         doLogRefresh();
        refresh++;
    }
    return {
        "total": res.total,//总页数
        "rows": res.list   //数据
    };
}

var index = null;

function onceCheck(value, row, $elem) {
    console.log(row.appid);
    if (refresh == 1 && appid != null && appid != 'null' && row.appid == appid) {
        index = $elem;
        setTimeout(function () {
            $("#dataTable > tbody > tr[data-index='" + index + "']").addClass("success");
            selectedRow = row;
            //右侧的刷新
            // doLogRefresh();
        }, 500);
        refresh++;
    }
    return value;
}
$(function () {
    newCheck.initByName('error_text');
    newCheck.initByName('del_text');
    initTextSearch("#pIsvName"
        ,basePath + 'bizApp/searchIsvList?t='+ (new Date()).getTime()+'&isvName='
        ,['isvPid','isvName'],{'isvPid':"服务商pid",'isvName':'服务商名称'}
        ,'isvName','isvName'
        ,true,
        selectPisvValue,
        noSelectPisvValue,
        false
    );
    initTextSearch("#isvName"
        ,basePath + 'bizApp/searchIsvList?t='+ (new Date()).getTime()+'&isvName='
        ,['isvPid','isvName']
        ,{'isvPid':"服务商pid",'isvName':'服务商名称'}
        ,'isvName'
        ,'isvName'
        ,true,
        selectIsvValue,
        noSelectIsvValue,
        false
    );

    regValidate(["#_bizDataForm"]);
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedRow = row;
            openEnumPage();
        },
    }

    initScanQrCodePage('minApp', 'publish', doPublishApp,closeScanOrCodePage,refreshQrCode);
});

function selectPisvValue(data){
    if (!data || !data.isvPid) {
        return;
    }
    $('#PisvPid').val(data.isvPid);
}
function noSelectPisvValue(){
    $('#PisvPid').val("");
}

function selectIsvValue(data){
    if (!data || !data.isvPid) {
        return;
    }
    $('#SisvPid').val(data.isvPid);
    $("#bizCode").val("");
    selectBiz(data.isvPid);
    doWinRefresh();
}
function noSelectIsvValue(){
    $('#SisvPid').val("");
}

function doRefresh() {
    selectedRow = null;
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridBizAppData?t=' + new Date().getTime(),
    });
}


function doLogRefresh() {
    $('#dataLogTable').bootstrapTable('refresh', {
        url: basePath + 'bizApp/getGridOrgLogData?t=' + new Date().getTime(),
    });
}


function getLogParams(params) {
    return {
        bizId : selectedRow.appid,
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
}

function add() {
    $("#SisvPid").val("");
    $("#bizCode").children().remove();
    $("#winOrgName").val("");
    $("#isvName").val("");
    doWinRefresh();
    $('#addBizApp').modal(true);
}
function selectBiz(isvPid) {
    $.ajax({
        type: 'post',
        url: basePath+ "bizApp/searchBizList",
        dataType: 'json',
        data:{isvPid:isvPid},
        success : function (data) {
          $("#bizCode").children().remove();
          var  Str = "<option value=''>--请选择--</option>";
          if(data.length > 0)
          for(var index in data){
              Str+= "<option value='" +data[index].bizCode+"'>" +data[index].bizName+
                  (data[index].childName == null?"":("（必备服务项："+data[index].childName+"）"))+"</option>"
          }
          $("#bizCode").append(Str);
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function formatStatus(value, row, index) {
    if (value == 'enabled') {
        return '有效';
    }
    if (value == 'disabled') {
        return '无效';
    }
    return value;
}

//左边选中事件
$("#dataTable").on("click-row.bs.table",function(e, row, $element){
    var index = $element[0].rowIndex - 1;
    $('#dataTable').bootstrapTable('uncheckAll');
    $('#dataTable').bootstrapTable('check', index);
    $("#dataTable .success").removeClass("success");
    $element.addClass("success");
    selectedRow = row;
    doLogRefresh();
});


function getParams(params) {
    var postData = {};
    $("#searchForm").serializeArray().map((function (item,index,input) {
        postData[item.name] = item.value;
    }));
    postData.appCategory = 'org';
    postData.isParent = '1';
    postData.pageSize =  params.pageSize;
    postData.pageNo =  params.pageNumber;
    console.log(postData);
    return postData;
}


function doWinRefresh() {
        $('#WinTable').bootstrapTable('refresh', {
            url: basePath + 'bizApp/getGridOrgData?t=' + new Date().getTime(),
        });
}

function getWinParams(params) {
    var fromDate = getFormData('#winfom');
    fromDate.pageSize =  params.pageSize;
    fromDate.pageNo =  params.pageNumber;
    fromDate.appCategory = 'org';
    if($("#SisvPid").val() != ""){
        fromDate.isvPid = $("#SisvPid").val();
    }
    if($("#bizCode").val() != ""){
        fromDate.bizCode = $("#bizCode").val();
    }
    return fromDate;
}

function changeBiz(e) {
   var bizCode = $("#bizCode").val();
    doWinRefresh();
}

function doSaveApp() {
    if($("#SisvPid").val() == ''){
        toastr.error("请选择服务商");
        return;
    }
    var bizCode = $.trim($("#bizCode").val());
    var bizName = $.trim($("#bizCode option:checked").text());
    if(bizCode == ''){
        toastr.error("请选择业务类型");
        return;
    }
    var selectRows = getSelectedRows("#WinTable");
    if(selectRows == null || selectRows.length == 0){
        toastr.error("请选择机构");
        return;
    }
    var list = new Array();
    for (var index in selectRows){
        list.push({
            refCode:selectRows[index].orgCode,
            isvPid:selectRows[index].isvPid,
            appName:bizName,
            appDisplayName:bizName,
            bizCode:bizCode
        });
    }
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/addBizApp',
        dataType: 'json',
        beforeSend:function () {
            showLoading()
        },
        complete:function(){
            hideLoading();
        },
        contentType: "application/json",
        data: JSON.stringify({isvPid:$("#SisvPid").val(),bizCode:bizCode,refDataList:list,appCategory:'org'}),
        success : function (data) {
            if(data.result){
                toastr.success(data.message);
                doRefresh();
                $("#addBizApp").modal('hide');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });

}

var VueObj = new Vue({
    el:"#editBizApp",
    data:{editBizApp:{}}
});
function edit() {
    if(selectedRow == null){
       toastr.error(common_no_choose_msg.format("操作"));
       return;
    }
    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能编辑");
        return;
    }
    onOpenEditEvent('edit', selectedRow.id);
    /*VueObj.$set(VueObj.$data,"editBizApp",JSON.parse(JSON.stringify(selectedRow)));
    $("#editBizApp").modal(true);*/
}

function onOpenEditEvent(command, id) {
    var searchStr = searchStrBefore("#searchForm","#dataTable");
    searchStr += ',selectAppId='+selectedRow.appid;
    window.location.href = basePath + 'bizApp/editOrgBizAppPage?editType=' + command + '&id=' + id + '&t=' + new Date().getTime() +
        '&isTeamExist=' + searchInfo.isTeamExist + '&isDocExist=' + searchInfo.isDocExist + '&searchStr=' + searchStr;
}


function doEditBiz() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }

    var postData = {};
    $("#editBizAppFrom").serializeArray().map((function (item,index,input) {
        postData[item.name] = item.value;
    }));
    postData.id = selectedRow.id;
    postData.isvPid = selectedRow.isvPid;
    postData.refCode = selectedRow.refCode;
    postData.bizCode = selectedRow.bizCode;
    postData.appCategory = selectedRow.appCategory;
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/editBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend:function () {
            showLoading()
        },
        complete:function(){
            hideLoading();
        },
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                toastr.success(data.message);
                doRefresh();
                $("#editBizApp").modal('hide');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function beforePubish() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }


    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能重复提交发布");
        return;
    }

    if(selectedRow.dataStatus == 'check_pass'){
        toastr.error("这是已审核数据不能重复提交发布");
        return;
    }

    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/beforePublish',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify({appid:selectedRow.appid,appCategory:'org'}),
        success : function (data) {
            if(data.result){
                // 家庭医生 显示 二维码
                if(showQrCode == selectedRow.bizCode){
                    publishAppWin();
                }else{
                    swal({
                        title: '提示',
                        text: "确定要发布这个机构服务吗？",
                        showCancelButton:"true",
                        showConfirmButton:"true",
                        confirmButtonText:"确定",
                        cancelButtonText:"取消",
                        animation:"slide-from-top"
                    }, function() {
                        doPublishApp();
                    });
                }
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


function publishAppWin() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }

    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能重复提交发布");
        return;
    }

    if(selectedRow.dataStatus == 'check_pass'){
        toastr.error("这是已审核数据不能重复提交发布");
        return;
    }

    // $.ajax({
    //     type: 'post',
    //     url: basePath + 'bizApp/updateQRCode',
    //     dataType: 'json',
    //     contentType: "application/json",
    //     data: JSON.stringify({id:selectedRow.id,appid:selectedRow.appid,orgCode:selectedRow.refCode,appCategory:selectedRow.appCategory}),
    //     success : function (data) {
    //         if(data.result){
    //             // //移除当前已生成数据
    //             $("#_validNum").text(data.content.validNum);
    //             $("#scanCode").attr("src",data.content.qrUrl);
    //             $("#publishApp").modal(true);
    //         }else{
    //             toastr.error(data.message);
    //         }
    //     },
    //     error: function (request) {
    //         toastr.error(common_system_error);
    //     }
    // });

    doShowQrCode( basePath + 'bizApp/updateQRCode',
        {id:selectedRow.id,appid:selectedRow.appid,orgCode:selectedRow.refCode,appCategory:selectedRow.appCategory},
        'minApp');
}

function doPublishApp() {
    var postData = {};
    postData.id = selectedRow.id;
    postData.appid = selectedRow.appid;
    postData.isvPid = selectedRow.isvPid;
    postData.refCode = selectedRow.refCode;
    postData.bizCode = selectedRow.bizCode;
    postData.appCategory = selectedRow.appCategory;
    postData.orgCode = selectedRow.orgCode;
    postData.status = selectedRow.status;
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/publishBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend:function () {
            showLoading();
            $("#upPublish").button('loading');
        },
        complete:function(){
            hideLoading();
            $("#upPublish").button('reset');
        },
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                toastr.success(data.message);
                doRefresh();
                closeScanOrCodePage();
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function unPublishAppwin() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }

    if(selectedRow.status == 'unpublished'){
        toastr.error("这是未发布数据无需撤销");
        return;
    }

    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能撤销");
        return;
    }

    $("input[name=error_text]").removeAttrs('checked');
    $("#error_textarea").val("");
    $("#unPublishAppWin").modal(true);
}

function doUnPublishApp() {
    var result = new Array();
    $("input[name=error_text]:checked").each(function (index,value) {
        result.push($(value).val());
    });
    if(result.length==0 && $("#error_textarea").val() == ''){
        toastr.error("请选择撤销原因");
        return;
    }
    result.push($("#error_textarea").val());
    // if(result.length==0){
    //     toastr.error("请选择撤销原因");
    //     return;
    // }
        var postData = {};
        postData.id = selectedRow.id;
        postData.appid = selectedRow.appid;
        postData.isvPid = selectedRow.isvPid;
        postData.refCode = selectedRow.refCode;
        postData.bizCode = selectedRow.bizCode;
        postData.appCategory = selectedRow.appCategory;
        postData.orgCode = selectedRow.orgCode;
        postData.status = selectedRow.status;
        postData.revokeRemark = result.join(",");
        $.ajax({
            type: 'post',
            url: basePath + 'bizApp/unPublishBizApp',
            dataType: 'json',
            beforeSend: function () {
                showLoading();
            },
            complete: function () {
                hideLoading();
            },
            contentType: "application/json",
            data: JSON.stringify(postData),
            success : function (data) {
                if(data.result){
                    toastr.success(data.message);
                    doRefresh();
                    // doLogRefresh();
                    $("#unPublishAppWin").modal("hide");
                }else{
                    toastr.error(data.message);
                }
            },
            error: function (request) {
                toastr.error(common_system_error);
            }
        });
}



function validateBizApp() {
    var postData = {};
    postData.refCode = selectedRow.refCode;
    postData.bizCode = selectedRow.bizCode;
    postData.appCategory = selectedRow.appCategory;
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/validateBizApp',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                deleteBatchApp();
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}


function deleteBatchApp() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    $("input[name=del_text]").removeAttrs('checked');
    $("#del_textarea").val("");
    if(selectedRow.dataStatus == 'pending_check'){
        toastr.error("这是待审核数据不能删除");
        return;
    }
    if(selectedRow.status == 'publish'){
        toastr.error("这是已发布数据，请先撤销再删除");
        return;
    }
    $("#delAppWin").modal(true);
}


function dodelApp() {
    var result = new Array();
    $("input[name=del_text]:checked").each(function (index,value) {
        result.push($(value).val());
    });
    if(result.length==0 && $("#del_textarea").val() == ''){
        toastr.error("请选择撤销原因");
        return;
    }
    result.push($("#del_textarea").val());
    var postData = {};
    postData.id = selectedRow.id;
    postData.appid = selectedRow.appid;
    postData.isvPid = selectedRow.isvPid;
    postData.refCode = selectedRow.refCode;
    postData.bizCode = selectedRow.bizCode;
    postData.appCategory = selectedRow.appCategory;
    postData.orgCode = selectedRow.orgCode;
    postData.status = selectedRow.status;
    postData.dataStatus = 'delete';
    postData.remark = result.join(",");
    $.ajax({
        type: 'post',
        url: basePath + 'bizApp/delBizApp',
        dataType: 'json',
        contentType: "application/json",
        beforeSend:function () {
            showLoading()
        },
        complete:function(){
            hideLoading();
        },
        data: JSON.stringify(postData),
        success : function (data) {
            if(data.result){
                toastr.success(data.message);
                doRefresh();
                $("#delAppWin").modal('hide');
            }else{
                toastr.error(data.message);
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function updateChildrenBiz() {
    if(selectedRow == null){
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    var searchStr = searchStrBefore("#searchForm","#dataTable");
    searchStr += ',selectAppId='+selectedRow.appid;
    var str = '&pIsvPid=' + selectedRow.isvPid + '&pIsvName=' + selectedRow.isvName +
        '&pOrgName=' + selectedRow.orgName +'&pBizName=' + selectedRow.bizName +
        '&pBizCode=' + selectedRow.bizCode + '&pRefCode=' + selectedRow.refCode;
   window.location.href = basePath+"bizApp/bizAppChildrenBiz?pAppId="+selectedRow.appid+"&t="+new Date().getTime()
       +"&searchStr="+searchStr + '&isTeamExist=' + searchInfo.isTeamExist + '&isDocExist=' + searchInfo.isDocExist + str;
}

function downaload() {
    $('#searchForm').attr("action",basePath+"bizApp/exportBizAppExcel");
    $('#searchForm').submit();
}

function publishDataStatus(value,row,index) {
    if(PushlishStatus != null){
                return PushlishStatus[value];
    }
    return "";
}

    function dataStatus(value,row,index) {
        if(DataStatus != null){
           return DataStatus[value];
        }
        return "";
    }

    function OperateTypeFormatter(value,row,index) {
        if(OperateType != null){
            return OperateType[value];
        }
        return "";
    }


function checkTypeFormatter(value,row,index) {
    if(resultTypeMap != null){
        return resultTypeMap[value];
    }
    return "";
}


function GmtCreateFormatter(value,row,index) {
    if(row.result == 'pass'){
        return row.gmtCreate;
    }else{
        return "";
    }
}



function refreshQrCode() {
    doShowQrCode( basePath + 'bizApp/updateQRCode',
        {id:selectedRow.id,appid:selectedRow.appid,orgCode:selectedRow.refCode,appCategory:selectedRow.appCategory},
        'minApp');
}


function closeScanOrCodePage() {
    $("#scanQrCodePage-common").modal('hide');
    $("#scanCodeMinApp").attr("src", '');
}